package com.application.lucky.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.application.lucky.R;
import com.application.lucky.bean.jsonBean.PeiLvBean;
import com.application.lucky.manager.RedManager;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.RedPRequest;
import com.application.lucky.utils.CTextUtils;
import com.application.lucky.widget.TitlebarView;
import com.application.lucky.widget.dialog.InputPassworDialog;
import com.application.mylibrary.base.BaseActivity;
import com.application.mylibrary.utils.ToastUtils;
import com.baselib.libnetwork.net.libnetworkcomponent.BaseResponse;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 发送红包界面
 */
public class SendRedPActivity extends BaseActivity {

    private TitlebarView mTitleBar;
    //    private TextView mTvSendRpNum;
    private EditText mEtSendRpInput;
    private RecyclerView mRclView;
    private Button mBtSendRpView;
    private TextView mTvMoneyQujian;
    private CheckBox mCbView;
    private RecyclerView mRclSelectMoney;
    private TextView mTvRpResult;
    private String id;

    private MyAdapter myAdapter2 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loaddata();
        initView();
        initListener();
    }

    private List<PeiLvBean> peiLvBeans = new ArrayList<>();

    private void loaddata() {
        new RedPRequest().red_multiple_list(new CallBackEx<BaseResponse<List<PeiLvBean>>>() {
            @Override
            public void onFailed(int code) {

            }

            @Override
            public void onSuccess(BaseResponse<List<PeiLvBean>> stringBaseResponse) {
                List<PeiLvBean> dataInfo = stringBaseResponse.dataInfo;

                if (dataInfo != null) {
                    peiLvBeans = dataInfo;
                }

            }
        });
    }

    private void initListener() {
        mTitleBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finishAnim();
            }

            @Override
            public void rightClick() {

            }
        });
//        mTvSendRpNum.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                showSelect();
//
//            }
//        });
        mEtSendRpInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    List<String> data2 = myAdapter2.getData();
                    int alreadyIndex = data2.indexOf(s.toString());
                    if (alreadyIndex >= 0 && alreadyIndex < data2.size()) {
                        myAdapter2.setSelectNum(alreadyIndex);
                    } else {
                        myAdapter2.clearSelect();
                    }
                } else {
                    myAdapter2.clearSelect();
                }

                if (checkMonkeyOk(s.toString())) {
                    updateTotalAndMultipleNumber();
                } else {
                    mTvRpResult.setText(getString(R.string.red_default_totle_money_mul));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mBtSendRpView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                new InputPayPwDialog(SendRedPActivity.this).show();

                String s = mEtSendRpInput.getText().toString();
//                String num = mTvSendRpNum.getText().toString();
//                if (TextUtils.isEmpty(num)) {
//                    ToastUtils.show("请先选择红包");
//                    return;
//                }
                Integer money = 0;
                int rpNum = 9;
                if (TextUtils.isEmpty(s)) {
                    ToastUtils.show("请输入金额");
                    return;
                }
                try {
                    if (s.startsWith("¥")) {
                        String substring = s.substring(1);
                        money = Integer.valueOf(substring);
                    } else {
                        money = Integer.valueOf(s);
                    }

//                    rpNum = Integer.valueOf(num);

                } catch (Exception e) {
                    ToastUtils.show("格式异常，请重新输入");
                    mEtSendRpInput.setText("");
                    return;
                }

                if (money < 100 || money > 2000) {
                    ToastUtils.show("必须是100-2000区间的整数，请重新输入");
                    mEtSendRpInput.setText("");
                    return;
                }

                if (money % 100 != 0) {
                    ToastUtils.show("必须是100的整数倍");
                    mEtSendRpInput.setText(String.valueOf(money / 100 * 100));
                    mEtSendRpInput.setSelection(mEtSendRpInput.getText().toString().length());

                    setMoneySelect(mEtSendRpInput.getText().toString());
                    return;
                }

                int selectNum = myAdapter.getSelectNum();
                if (selectNum < 3) {
                    ToastUtils.show("至少选择三个雷点！");
                    return;
                }
                String select = myAdapter.getSelect();
//                money/=10;

//                final Integer finalMoney = money;
                if (dialog==null) {
                    dialog = new InputPassworDialog(SendRedPActivity.this, new InputPassworDialog.SendSuccessListener() {
                        @Override
                        public void success() {
                            mEtSendRpInput.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finishAnim();
                                }
                            },300);


                        }


                    });
                }

                dialog.setData(id, money.toString(), rpNum + "", select);
                dialog.show();

            }
        });

    }
    InputPassworDialog dialog;

    @Override
    public void beforeInit() {
        id = getIntent().getStringExtra("id");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_send_red_p;
    }

    MyAdapter myAdapter;

    private void initView() {
        mTitleBar = findViewById(R.id.title_bar);
//        mTvSendRpNum = findViewById(R.id.tv_send_rp_num);
        mEtSendRpInput = findViewById(R.id.et_send_rp_input);
        mRclView = findViewById(R.id.rcl_view);

        mRclView.setLayoutManager(new GridLayoutManager(this, 3));
        String[] stringArray = getResources().getStringArray(R.array.send_rp_button);
        List<String> strings = Arrays.asList(stringArray);

        myAdapter = new MyAdapter(true);
        myAdapter.setNewData(strings);
        myAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                try {
//                    String rpNum = mTvSendRpNum.getText().toString();
//                    if (TextUtils.isEmpty(rpNum)) {
//                        ToastUtils.show("请先选择红包数量");
//                        return;
//                    }

                    if (position < 9 || position == 10) {
                        myAdapter.setSelectNum(position);
                        updateTotalAndMultipleNumber();
                    } else if (position == 11) {
                        myAdapter.clearSelect();
                        mEtSendRpInput.setText("");
                        myAdapter2.clearSelect();

                        mTvRpResult.setText(getString(R.string.red_default_totle_money_mul));
                    } else if (position == 9) {
                        String mOney = RedManager.getMOney();
                        List<String> leidian = RedManager.getLeidian();
                        setMoneySelect(mOney);
                        if (leidian != null && leidian.size() > 0) {
                            myAdapter.setSelectNum(leidian);
                        }

                        updateTotalAndMultipleNumber();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        mRclView.setAdapter(myAdapter);
        mBtSendRpView = findViewById(R.id.bt_send_rp_view);
        mTvMoneyQujian = findViewById(R.id.tv_money_qujian);
        mCbView = findViewById(R.id.cb_view);
        mCbView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                RedManager.saveCHeck(b);
            }
        });
        mCbView.setChecked(RedManager.isCheck());
//        if (RedManager.isCheck()) {
        String mOney = RedManager.getYuShe();
        if (mOney != null) {
            mEtSendRpInput.setText(mOney);
            mEtSendRpInput.setSelection(mOney.length());
        }
//        }

        mRclSelectMoney = findViewById(R.id.rcl_select_money);
        String[] stringArray2 = getResources().getStringArray(R.array.send_rp_money_button);
        List<String> strings2 = Arrays.asList(stringArray2);

        myAdapter2 = new MyAdapter(false);
        myAdapter2.setNewData(strings2);
        myAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                myAdapter2.setSelectNum(position);
                mEtSendRpInput.setText(myAdapter2.getItem(position));

                updateTotalAndMultipleNumber();
            }
        });
        mRclSelectMoney.setLayoutManager(new GridLayoutManager(this, 5));
        mRclSelectMoney.setAdapter(myAdapter2);
        mTvRpResult = findViewById(R.id.tv_rp_result);
    }

    static class MyAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        List<String> selectNum = new ArrayList<>();

        public int getSelectNum() {
            return selectNum.size();
        }

        public void setSelectNum(List<String> selectNum) {
            this.selectNum = selectNum;
            notifyDataSetChanged();
        }

        public void clearSelect() {
            selectNum.clear();
            notifyDataSetChanged();
        }

        private boolean isSelectNUm;

        public MyAdapter(boolean isSelect) {
            super(R.layout.item_group_send_rp_button);
            this.isSelectNUm = isSelect;
        }

        public boolean isSelect(int s) {
            return selectNum.contains(s + "");
        }

        public String getSelect() {
            Collections.sort(selectNum);
            StringBuffer sb = new StringBuffer();
            boolean isHave0 = false;
            for (String s : selectNum) {
//                isHave0 = false;
                if ("10".equals(s)) {
//                    s = "-1";
                    isHave0 = true;
                    continue;
                }
                sb.append(Integer.valueOf(s) + 1).append(",");

            }
            if (isHave0) {
                sb.append("0,");
            }
            String s = sb.toString();
            String substring = s.substring(0, s.length() - 1);
            return substring;
        }

        public void setSelectNum(int position) {
            if (isSelectNUm) {
                if (selectNum.contains(position + "")) {
                    selectNum.remove(position + "");
                } else {
                    if (selectNum.size() == 9) {
                        return;
                    }
                    selectNum.add(position + "");
                }
                notifyItemChanged(position);
            } else {
                selectNum.clear();
                selectNum.add(position + "");
                notifyDataSetChanged();
            }

        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            boolean contains = selectNum.contains(helper.getAdapterPosition() + "");
            helper.setText(R.id.tv_num_view, item).
                    setTextColor(R.id.tv_num_view, contains ? Color.parseColor("#ffffff") : Color.parseColor("#111111")).
                    setBackgroundRes(R.id.rl_view, contains ? R.drawable.shape_domain_text_cor_4 : R.drawable.shape_white_cor_4);
        }
    }

    private void setMoneySelect(String money) {
        if (!TextUtils.isEmpty(money)) {
            List<String> data2 = myAdapter2.getData();
            int alreadyIndex = data2.indexOf(money);
            if (alreadyIndex >= 0 && alreadyIndex < data2.size()) {
                myAdapter2.setSelectNum(alreadyIndex);
                mEtSendRpInput.setText(money);
                mEtSendRpInput.setSelection(money.length());
            }
        }
    }

    private void updateTotalAndMultipleNumber() {
        int selectNum = myAdapter.getSelectNum();
        if (selectNum < 3) {
            mTvRpResult.setText(getString(R.string.red_default_totle_money_mul));
            return;
        }
        if (peiLvBeans != null) {
            int money = 0;
            String s = mEtSendRpInput.getText().toString();
            if (s.startsWith("¥")) {
                String substring = s.substring(1);
                money = Integer.valueOf(substring);
            } else {
                money = Integer.valueOf(s);
            }
            for (PeiLvBean peiLvBean : peiLvBeans) {
                if (peiLvBean.getRedXNum() == selectNum) {
                    int awardMoney = peiLvBean.getRedMultipleNum() * money;

                    CTextUtils.getBuilder("可赢金额：")
                            .append(awardMoney + "").setForegroundColor(Color.parseColor("#DE3F35"))
                            .append(" 游戏倍数：").append(peiLvBean.getRedMultipleNum() + "").into(mTvRpResult);
                }
            }
        }
    }

    private boolean checkMonkeyOk(String s) {
        if (TextUtils.isEmpty(s)) {
            return false;
        }

        try {
            int money = Integer.parseInt(s);
            if (money >= 100 && money <= 2000) {
                return money % 100 == 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        getWindowManager().removeView(view);
    }
}
